#!/usr/bin/python3
#
# analog: Remote logging manager for the Red Hat Installer
#
# Copyright (C) 2010
# Red Hat, Inc.  All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import getpass
# FIXME: we should not use optparse anymore
import optparse  # pylint: disable=deprecated-module
import os
import os.path
import sys

DEFAULT_PORT = 6080
DEFAULT_ANALOG_DIR = '.analog'
USAGE = "%prog [options] <log directory root>"
HINT = "/sbin/rsyslogd -c 5 -f %(conf)s -i %(pid)s"
PID_LOCATION = "/tmp/%(username)s/rsyslogd_%(unique_id)s.pid"

INPUT_TCP_TEMPLATE = "$InputTCPServerRun %(port)s"
INPUT_SOCKET_TEMPLATE = "$AddUnixListenSocket %(socket)s"

RSYSLOG_TEMPLATE ="""
#### MODULES ####
# Provides TCP syslog reception
$ModLoad imtcp.so
$ModLoad imuxsock
$OmitLocalLogging on
$SystemLogRateLimitInterval 0
%(input_directive)s

#### GLOBAL DIRECTIVES ####

# Use default timestamp format
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

# File syncing capability is disabled by default. This feature is usually not
# required, not useful and an extreme performance hit.
#$ActionFileEnableSync on


#### RULES ####

$template anaconda_justmsg, "%%msg%%\\n"
$template anaconda_debug, "%%rawmsg%%\\n"
$template anaconda_syslog, "%%timestamp:8:$:date-rfc3164%%,%%timestamp:1:3:date-subseconds%% %%syslogseverity-text:::uppercase%% %%programname%%:%%msg%%\\n"

$template path_syslog, "%(directory)s/%(subdirectory)s/syslog
$template path_anaconda, "%(directory)s/%(subdirectory)s/anaconda.log"
$template path_anaconda_tb, "%(directory)s/%(subdirectory)s/anaconda-tb-all.log"
$template path_program, "%(directory)s/%(subdirectory)s/program.log"
$template path_storage, "%(directory)s/%(subdirectory)s/storage.log"
$template path_xserver, "%(directory)s/%(subdirectory)s/X.log"
$template path_ifcfg, "%(directory)s/%(subdirectory)s/ifcfg.log"
$template path_sysimage, "%(directory)s/%(subdirectory)s/install.log.syslog"

*.*                                                  %(directory)s/debug_all.log;anaconda_debug

kern.*;\\
daemon.*;\\
user.info;\\
authpriv.*                                          ?path_syslog;anaconda_syslog

:programname, isequal, "anaconda"                   ?path_anaconda;anaconda_syslog
:programname, isequal, "anaconda-tb"                ?path_anaconda_tb;anaconda_justmsg
:programname, isequal, "program"                    ?path_program;anaconda_syslog
:programname, isequal, "storage"                    ?path_storage;anaconda_syslog
:programname, isequal, "xserver"                    ?path_xserver;anaconda_justmsg
:programname, isequal, "ifcfg"                      ?path_ifcfg;anaconda_syslog
:hostname, isequal, "sysimage"                      ?path_sysimage;anaconda_syslog

# discard those that we logged
:programname, isequal, "rsyslogd"                    ~
:programname, isequal, "anaconda"                    ~
:programname, isequal, "anaconda-tb"                 ~
:programname, isequal, "program"                     ~
:programname, isequal, "storage"                     ~
:programname, isequal, "xserver"                     ~
:programname, isequal, "ifcfg"                       ~
:hostname, isequal, "sysimage"                       ~
kern.*                                               ~
daemon.*                                             ~
authpriv.*                                           ~
user.info                                            ~
# dump the rest
*.*                                                  %(directory)s/debug_unknown_source.log;anaconda_debug

"""

# option parsing
class OptParserError(Exception):
    def __str__(self):
        return self.args[0]  # pylint: disable=unsubscriptable-object

    @property
    def parser(self):
        return self.args[1]  # pylint: disable=unsubscriptable-object

def absolute_path(input_path):
    """
    If the path doesn't start with a slash, consider it relative to the current
    working directory.

    Returns aboslute path of 'path'.
    """
    path = os.path.join(os.getcwd(), input_path)
    path = os.path.abspath(path)
    return path

def build_unique_id(options):
    unique_id = options.unix_socket or str(options.port)
    # could be full path to the socket, strip everything before the last slash
    unique_id = unique_id.rsplit('/', 2)[-1]
    return unique_id

def get_opts():
    parser = optparse.OptionParser(usage=USAGE,
                                   add_help_option=False)
    parser.add_option ('-h', '--help', action="callback", callback=help_and_exit,
                       help="Display this help")
    parser.add_option ('-o', type="string", dest="output",
                       default=None,
                       help="Output file")
    parser.add_option ('-p', type="int", dest="port",
                       default=DEFAULT_PORT,
                       help="TCP port the rsyslog daemon will listen on")
    parser.add_option ('-s', action="store_true", dest="stdout",
                       default=False,
                       help="Generate bash command to run rsyslogd on stdout (only valid when -o is also specified)")
    parser.add_option ('-u', type="string", dest="unix_socket",
                       default=None,
                       help="Unix socket the rsyslog daemon will listen on. Using this option turns off listening for TCP connections.")

    (options, args) = parser.parse_args()
    if len(args) < 1:
        raise OptParserError("no log root directory given", parser)
    if options.stdout and not options.output:
        raise OptParserError("-s only valid with -o", parser)
    options.log_root = absolute_path(args[0])
    if options.unix_socket:
        options.unix_socket = absolute_path(options.unix_socket)
    args = args[1:]
    return (options, args)

def help_and_exit(option, opt, value, parser):
    parser.print_help()
    sys.exit(0)

def generate_rsyslog_config(options, unique_id):
    values = {
        "input_directive" : INPUT_TCP_TEMPLATE % {'port' : options.port},
        "directory" : options.log_root,
        "subdirectory" : "%FROMHOST-IP%"
        }

    if options.unix_socket:
        values["input_directive"] = INPUT_SOCKET_TEMPLATE % {'socket' : options.unix_socket}
        values["subdirectory"] = unique_id

    config = RSYSLOG_TEMPLATE % values
    return config

def pid_location(unique_id):
    # find the target location
    name = getpass.getuser()
    values = {
        "username" : name,
        "unique_id" : unique_id
        }
    location = PID_LOCATION % values
    # now make sure the directory exists
    directory = os.path.dirname(location)
    if not os.path.exists(directory):
        os.mkdir(directory)
    return location

def main():
    try:
        (options, _args) = get_opts()
    except OptParserError as exc:
        exc.parser.error(str(exc))
        sys.exit(1)
    unique_id = build_unique_id(options)
    config = generate_rsyslog_config(options, unique_id)
    if options.output:
        options.output = os.path.abspath(options.output)
        try:
            with open(options.output, 'w') as f:
                f.write(config)
        except OSError:
            print("Can't write into file %s" % options.output, file=sys.stderr)
            sys.exit(1)
        if options.stdout:
            pid = pid_location(unique_id)
            print(HINT % {
                    "conf" : options.output,
                    "pid" : pid
                    })
    else:
        print(config)

if __name__ == "__main__":
    main()
